package com.banksoft.cps.service.impl;

import com.banksoft.cps.bean.MonitorValue;
import com.banksoft.cps.bean.MonitorValueImport;
import com.banksoft.cps.bean.common.ServiceException;
import com.banksoft.cps.dao.DeviceDao;
import com.banksoft.cps.dao.MonitorValueDao;
import com.banksoft.cps.dao.MonitorValueImportDao;
import com.banksoft.cps.service.MonitorValueService;
import com.banksoft.cps.util.DateUtil;
import com.banksoft.cps.util.ExcelUtil;
import com.banksoft.cps.util.UUIDFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by rongzhao.zhu on 2018/2/24.
 */
@Service
public class MonitorValueServiceImpl implements MonitorValueService {
    @Autowired
    MonitorValueDao monitorValueDao;
    @Autowired
    DeviceDao deviceDao;
    @Autowired
    MonitorValueImportDao monitorValueImportDao;
    @Override
    public MonitorValue findBySaleOrderId(String saleOrderId) {
        return monitorValueDao.findBySaleOrderId(saleOrderId);
    }

    @Override
    public void importMonitorValue(String deviceId, String excelPath) throws ServiceException {
        try {
            Map<Integer,String> keyMap = new HashMap<>();
            keyMap.put(0,"monitorTimeStr");
            keyMap.put(1,"value");
            List<MonitorValueImport> list =   ExcelUtil.read(excelPath,
                    MonitorValueImport.class,keyMap);
            long now = System.currentTimeMillis();
            if(!list.isEmpty()){
                for(int i = 0; i<list.size();i++){
                    MonitorValueImport monitorValueImport = list.get(i);
                    monitorValueImport.setId(UUIDFactory.random());
                    monitorValueImport.setDeviceId(deviceId);
                    monitorValueImport.setCreateTime(now);
                    monitorValueImport.setMonitorTime(DateUtil.getTime2(monitorValueImport.getMonitorTimeStr()));
                }
            }
            int maxSize =  1000;

            for(int index = 0;index< list.size()-1 ;index = index +maxSize){
                List<MonitorValueImport> subList = null;
                if(index +maxSize <list.size() ){
                    subList = list.subList(index,index +maxSize);
                }else{
                     subList = list.subList(index,list.size()-1);
                }
                monitorValueImportDao.batchInsert(subList);
            }

            System.out.print("ox");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(100,"数据格式错误");
        }
    }
}
